package com.shop.cereshop.admin.service.report.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.admin.dao.buyer.CereBuyerUserDAO;
import com.shop.cereshop.admin.dao.report.CereReportRecordDAO;
import com.shop.cereshop.admin.page.report.ReportDetailVO;
import com.shop.cereshop.admin.page.report.ReportRecordPageVO;
import com.shop.cereshop.admin.param.buyer.BuyerGetUsersParam;
import com.shop.cereshop.admin.param.report.ReportAuditParam;
import com.shop.cereshop.admin.param.report.ReportHandleParam;
import com.shop.cereshop.admin.param.report.ReportPageParam;
import com.shop.cereshop.admin.redis.service.UserRedisService;
import com.shop.cereshop.admin.service.buyer.CereBuyerUserService;
import com.shop.cereshop.admin.service.report.CereReportRecordService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.disable.BuyerDisableTime;
import com.shop.cereshop.commons.domain.report.CereReportRecord;
import com.shop.cereshop.commons.domain.report.CereReportHandleLog;
import com.shop.cereshop.commons.domain.recommend.CereRecommendTrends;
import com.shop.cereshop.commons.domain.recommend.CereRecommendComment;
import com.shop.cereshop.commons.domain.user.CerePlatformUser;
import com.shop.cereshop.commons.enums.report.ReportStatusEnum;
import com.shop.cereshop.commons.enums.report.ReportAuditResultEnum;
import com.shop.cereshop.commons.enums.report.ReportHandleResultEnum;
import com.shop.cereshop.commons.enums.report.ReportHandleActionEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.StringUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.shop.cereshop.admin.dao.disable.BuyerDisableTimeDAO;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 举报记录服务实现类
 *
 * @author
 */
@Service
@Slf4j
public class CereReportRecordServiceImpl implements CereReportRecordService {

    @Autowired
    private CereReportRecordDAO cereReportRecordDAO;

    @Autowired
    private BuyerDisableTimeDAO buyerDisableTimeDAO;
    @Autowired
    private com.shop.cereshop.admin.dao.recommend.CereRecommendTrendsDAO cereRecommendTrendsDAO;
    
    @Autowired
    private com.shop.cereshop.admin.dao.recommend.CereRecommendCommentDAO cereRecommendCommentDAO;

    @Autowired
     private CereBuyerUserService cereBuyerUserService;

    @Autowired
    private CereBuyerUserDAO cereBuyerUserDAO;

    @Autowired
    private UserRedisService userRedisService;

    @Override
    public Page<ReportRecordPageVO> getReportPage(ReportPageParam param) throws CoBusinessException {
        // 设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());
        
        // 查询举报记录
        List<ReportRecordPageVO> list = cereReportRecordDAO.getReportPage(param);
        for (ReportRecordPageVO item : list) {
//            Long reportedUserId = item.getReportedUserId();
//            Long reporterUserId = item.getReporterUserId();
//            String reporterNickname = item.getReporterNickname();
//            String reportedNickname = item.getReportedNickname();
//            Long targetId = item.getTargetId();
//            if (reportedUserId != null) {
//                item.setReporterUserId(Long.valueOf(StringUtils.showStartAndEnd(reportedUserId.toString(),1,1)));
//            }
//            if (reporterUserId != null) {
//                item.setReporterUserId(Long.valueOf(StringUtils.showStartAndEnd(reporterUserId.toString(),1,1)));
//            }
//            if (reporterNickname != null) {
//                item.setReporterNickname(StringUtils.showStartAndEnd(reporterNickname,1,1));
//            }
//            if (reportedNickname != null) {
//                item.setReportedNickname(StringUtils.showStartAndEnd(reportedNickname,1,1));
//            }
//            if (targetId != null) {
//                item.setTargetId(Long.valueOf(StringUtils.showStartAndEnd(targetId.toString(),1,1)));
//            }
        }
        PageInfo<ReportRecordPageVO> pageInfo = new PageInfo<>(list);
        
        return new Page<>(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public ReportDetailVO getReportDetail(Long reportId) throws CoBusinessException {
        if (reportId == null) {
            throw new CoBusinessException(CoReturnFormat.FAIL, "举报ID不能为空");
        }
        
        ReportDetailVO detail = cereReportRecordDAO.getReportDetail(reportId);
//对举报人机号进行脱敏
        detail.setReporterPhone(StringUtils.showStartAndEnd(detail.getReporterPhone(),1,1));
//        对被举报人手机号进行脱敏
        detail.setReportedPhone(StringUtils.showStartAndEnd(detail.getReportedPhone(),1,1));
        if (detail == null) {
            throw new CoBusinessException(CoReturnFormat.REPORT_NOT_EXISTS);
        }
        
        return detail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditReport(ReportAuditParam param, CerePlatformUser user) throws CoBusinessException {
        // 参数校验已在Controller层通过@Validated注解完成
        
        // 查询举报记录
        CereReportRecord reportRecord = cereReportRecordDAO.selectById(param.getReportId());
        if (reportRecord == null) {
            throw new CoBusinessException(CoReturnFormat.REPORT_NOT_EXISTS);
        }
        
        // 检查状态：只有待审核状态才能审核
        if (!ReportStatusEnum.PENDING.getCode().equals(reportRecord.getReportStatus())) {
            throw new CoBusinessException(CoReturnFormat.FAIL, "只有待审核状态的举报才能审核");
        }
        
        // 更新举报记录
        CereReportRecord updateRecord = new CereReportRecord();
        updateRecord.setReportId(param.getReportId());
        updateRecord.setAuditUserId(user.getPlatformUserId());
        updateRecord.setAuditTime(TimeUtils.yyMMddHHmmss());
        updateRecord.setAuditResult(param.getAuditResult());
        updateRecord.setAuditRemark(param.getAuditRemark());
        
        // 根据审核结果设置状态
        if (ReportAuditResultEnum.VIOLATION.getCode().equals(param.getAuditResult())) {
            // 违规，设置为审核中，等待处理
            updateRecord.setReportStatus(ReportStatusEnum.AUDITING.getCode());
        } else {
            // 不违规，直接设置为已处理
            updateRecord.setReportStatus(ReportStatusEnum.PROCESSED.getCode());
        }
        
        updateRecord.setUpdateTime(TimeUtils.yyMMddHHmmss());
        
        int result = cereReportRecordDAO.updateById(updateRecord);
        if (result <= 0) {
            throw new CoBusinessException(CoReturnFormat.FAIL);
        }
        
        // 记录处理日志
        saveHandleLog(param.getReportId(), user.getPlatformUserId(), 
                ReportHandleActionEnum.AUDIT.getCode(), param.getAuditResult(), 
                param.getAuditRemark());
        
        log.info("管理员{}审核举报成功，举报ID：{}，审核结果：{}", 
                user.getPlatformUserId(), param.getReportId(), param.getAuditResult());
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleReport(ReportHandleParam param, CerePlatformUser user,HttpServletRequest request) throws CoBusinessException {
        // 参数校验已在Controller层通过@Validated注解完成
        
        // 查询举报记录
        CereReportRecord reportRecord = cereReportRecordDAO.selectById(param.getReportId());
        if (reportRecord == null) {
            throw new CoBusinessException(CoReturnFormat.REPORT_NOT_EXISTS);
        }
        
        // 检查状态：只有审核中状态才能处理
        if (!ReportStatusEnum.AUDITING.getCode().equals(reportRecord.getReportStatus())) {
            throw new CoBusinessException(CoReturnFormat.FAIL, "只有审核中状态的举报才能处理");
        }
        
        // 更新举报记录
        CereReportRecord updateRecord = new CereReportRecord();
        updateRecord.setReportId(param.getReportId());
        updateRecord.setHandleResult(param.getHandleResult());
        updateRecord.setHandleRemark(param.getHandleRemark());
        updateRecord.setReportStatus(ReportStatusEnum.PROCESSED.getCode());
        updateRecord.setUpdateTime(TimeUtils.yyMMddHHmmss());
        
        int result = cereReportRecordDAO.updateById(updateRecord);
        if (result <= 0) {
            throw new CoBusinessException(CoReturnFormat.FAIL);
        }
        
        // 记录处理日志
        saveHandleLog(param.getReportId(), user.getPlatformUserId(), 
                ReportHandleActionEnum.HANDLE.getCode(), param.getHandleResult(), 
                param.getHandleRemark());
        
        // 根据处理结果执行相应操作
        executeHandleAction(param.getHandleResult(),param.getBanTime(), reportRecord,request);
        
        log.info("管理员{}处理举报成功，举报ID：{}，处理结果：{}", 
                user.getPlatformUserId(), param.getReportId(), param.getHandleResult());
        
        return true;
    }

    @Override
    public Object getReportStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 统计待审核举报数量
        Integer pendingCount = cereReportRecordDAO.countPendingReports();
        stats.put("pendingCount", pendingCount);
        
        // 统计今日举报数量
        Integer todayCount = cereReportRecordDAO.countTodayReports();
        stats.put("todayCount", todayCount);
        
        // 统计总举报数量
        ReportPageParam param = new ReportPageParam();
        Integer totalCount = cereReportRecordDAO.countReports(param);
        stats.put("totalCount", totalCount);
        
        return stats;
    }
    
    /**
     * 保存处理日志
     */
    private void saveHandleLog(Long reportId, Long handleUserId, Integer handleAction, 
                              Integer handleResult, String handleRemark) {
        try {
            CereReportHandleLog handleLog = new CereReportHandleLog();
            handleLog.setReportId(reportId);
            handleLog.setHandleUserId(handleUserId);
            handleLog.setHandleAction(handleAction);
            handleLog.setHandleResult(handleResult);
            handleLog.setHandleRemark(handleRemark);
            handleLog.setHandleTime(TimeUtils.yyMMddHHmmss());
            
            // 这里需要注入CereReportHandleLogDAO来保存日志
            // cereReportHandleLogDAO.insert(handleLog);
            
            log.info("保存举报处理日志成功，举报ID：{}，处理动作：{}", reportId, handleAction);
        } catch (Exception e) {
            log.error("保存举报处理日志失败，举报ID：{}", reportId, e);
        }
    }
    
    /**
     * 执行处理动作
     */
    private void executeHandleAction(Integer handleResult, Long banTime,CereReportRecord reportRecord,HttpServletRequest request) {
        try {
            if (ReportHandleResultEnum.DELETE_CONTENT.getCode().equals(handleResult)) {
                // 删除内容
                deleteTargetContent(reportRecord.getTargetType(), reportRecord.getTargetId());
            } else if (ReportHandleResultEnum.WARN_USER.getCode().equals(handleResult)) {
                // 警告用户
                warnUser(reportRecord.getReportedUserId());
            } else if (ReportHandleResultEnum.BAN_USER.getCode().equals(handleResult)) {
                // 永久封禁用户
//                清楚用户的token
                userRedisService.clearAllTokens(reportRecord.getReportedUserId());
                banUser(reportRecord.getReportedUserId(),request);
            }
//            定时封禁用户
            else if (ReportHandleResultEnum.BAN_USER_TIMED.getCode().equals(handleResult)){
                banUserTimed(reportRecord.getReportedUserId(),banTime);
            }
        } catch (Exception e) {
            log.error("执行处理动作失败，举报ID：{}，处理结果：{}", 
                    reportRecord.getReportId(), handleResult, e);
        }
    }
    
    /**
     * 删除目标内容
     */
    private void deleteTargetContent(Integer targetType, Long targetId) {
        try {
            if (targetType == 1 || targetType == 2) {
                // 动态类型(1)或视频类型(2)：将publish_status修改为3(被举报下架)
                CereRecommendTrends trends = new CereRecommendTrends();
                trends.setRecommendId(targetId);
                trends.setPublishStatus(3); // 3-被举报下架
                trends.setUpdateTime(TimeUtils.yyMMddHHmmss());
                
                int result = cereRecommendTrendsDAO.updateById(trends);
                if (result > 0) {
                    log.info("成功将动态内容状态修改为被举报下架，动态ID：{}", targetId);
                } else {
                    log.warn("修改动态内容状态失败，动态ID：{}", targetId);
                }
            } else if (targetType == 3) {
                // 评论类型：删除评论及其所有子评论
                deleteCommentAndReplies(targetId);
            } else if (targetType == 4) {
                // 用户类型：这里可以添加用户相关处理逻辑
                log.info("处理用户相关操作，用户ID：{}", targetId);
                // TODO: 实现用户相关处理逻辑
            }
        } catch (Exception e) {
            log.error("删除目标内容失败，类型：{}，ID：{}", targetType, targetId, e);
        }
    }
    
    /**
     * 删除评论及其所有子评论
     */
    private void deleteCommentAndReplies(Long commentId) {
        try {
            // 先查询评论信息，判断是否为根评论
            CereRecommendComment comment = cereRecommendCommentDAO.getCommentById(commentId);
            if (comment == null) {
                log.warn("评论不存在，评论ID：{}", commentId);
                return;
            }
            
            int deletedCount = 0;
            
            if (comment.getRootCommentId() == null || comment.getRootCommentId().equals(commentId)) {
                // 如果是根评论，删除所有子评论
                deletedCount = cereRecommendCommentDAO.deleteCommentByRootCommentId(commentId);
                log.info("删除根评论及其所有子评论，根评论ID：{}，删除数量：{}", commentId, deletedCount);
            } else {
                // 如果是子评论，只删除当前评论
                deletedCount = cereRecommendCommentDAO.deleteComment(commentId);
                log.info("删除子评论，评论ID：{}，删除数量：{}", commentId, deletedCount);
            }
            
            if (deletedCount > 0) {
                log.info("成功删除评论，评论ID：{}，删除数量：{}", commentId, deletedCount);
            } else {
                log.warn("删除评论失败，评论ID：{}", commentId);
            }
        } catch (Exception e) {
            log.error("删除评论失败，评论ID：{}", commentId, e);
        }
    }
    
    /**
     * 警告用户
     */
    private void warnUser(Long userId) {
        // 实现用户警告逻辑
        log.info("警告用户，用户ID：{}", userId);
    }
    
    /**
     * 封禁用户
     */
    private void banUser(Long userId, HttpServletRequest request) throws CoBusinessException {
        // 实现用户封禁逻辑
        BuyerGetUsersParam buyerGetUsersParam = new BuyerGetUsersParam();
        buyerGetUsersParam.setBuyerUserId(userId);
        buyerGetUsersParam.setState(0);
        cereBuyerUserService.updateAccount(buyerGetUsersParam,request);
        log.info("封禁用户，用户ID：{}", userId);
    }
    /**
     * 定时封禁用户
     */
    private  void  banUserTimed(Long userId, Long banTime) throws CoBusinessException {
        // 使用 LocalDateTime 替代 DateTime
        LocalDateTime now = LocalDateTime.now();

        // 计算封禁结束时间（注意：LocalDateTime 没有毫秒级操作，需转换为 Instant 或使用 Duration）
        long nowMillis = System.currentTimeMillis();
        long banTimeStamp = nowMillis + banTime;

        // 将时间戳转为 LocalDateTime（需先转为 Instant）
        LocalDateTime banTimeDateTime = Instant.ofEpochMilli(banTimeStamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        BuyerDisableTime buyerDisableTime = new BuyerDisableTime();
        buyerDisableTime.setCreatTime(now); // 正确类型
        buyerDisableTime.setBuyerId(userId);
        buyerDisableTime.setDisableTime(banTimeDateTime);
        buyerDisableTimeDAO.insert(buyerDisableTime);
//        更该用户的状态
        cereBuyerUserDAO.updateState(userId);
    }


}
